package artid.com.arttogo.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;

import java.util.ArrayList;
import java.util.List;

import artid.com.arttogo.R;
import artid.com.arttogo.adapter.CertificationItems_Adapter;
import artid.com.arttogo.adapter.HotSpecial_Adapter;
import artid.com.arttogo.adapter.RecentAuction_Adapter;
import artid.com.arttogo.bean.AuctionHomeParser;
import artid.com.arttogo.bean.RecomAuctionListParser;
import artid.com.arttogo.bean.ShareItem;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.AppUrl;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.MySharedPreferences;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.view.MyAdGallery;
import artid.com.arttogo.view.MyListView;
import artid.com.arttogo.view.horizonlistview.HorizonListviewNestingListView;
import artid.com.arttogo.view.pulllist.PullToRefreshLayout;
import artid.com.arttogo.view.pulllist.PullableScrollView;

/**
 * 项目名称：ArtworkArt
 * 类名称：AuctionHomeActivity
 * 类描述：拍卖行首页
 * 创建人：耿卫斌
 * 创建时间：2017-2-28 下午2:30:13
 */
public class AuctionHomeActivity extends BaseActivity implements OnClickListener {
    Boolean isRequs = false;//判断是否在请求，用与解决缓存重复加载轮播图的问题。
    //页面缓存
    String strCacheView;
    String strCacheList;
    String TAG_CACHE_VIEW = "AuctonViewCache";
    String TAG_CACHE_LIST = "AuctionListCache";
    MySharedPreferences mSharePre;
    private MyAdGallery mMyAdGallery; // 广告控件
    private ViewGroup mMyAdGalleryGroup;//图片轮播指示器控件
    private ArrayList<String> mMyAdGalleryUrl = null;
    private PullToRefreshLayout mPullToRefreshLayout;
    private PullableScrollView mPullableScrollView;
    private RelativeLayout lunbo;
    private RelativeLayout pastAuctionBtn, auctionCatalogueBtn, celebritySealBtn, mechanismBtn;
    private TextView HideTitleName;
    private RelativeLayout titleRL, auctionHome_RL, CertificationItemsRL, hotSpecialRL;
    private ImageView backBtn, shareBtn;
    private artid.com.arttogo.view.horizonlistview.HorizonListviewNestingListView mHorizonListview_CertificationItems, mHorizonListview_HotSpecial;
    private CertificationItems_Adapter adapter_CertificationItems;
    private HotSpecial_Adapter adapter_HotSpecial;
    private RecentAuction_Adapter adapter_RecentAuction;
    private MyListView mListView;
    private boolean isRefreshed = false;// 是否刷新
    private int page = 1;
    private String imgHeight;//请求的图片高度度
    private List<AuctionHomeParser.AuctionHomeAdvs> advsList = new ArrayList<AuctionHomeParser.AuctionHomeAdvs>();//广告模块
    private List<AuctionHomeParser.AuctionHomeLotinfo> lotinfoList = new ArrayList<AuctionHomeParser.AuctionHomeLotinfo>();//推荐备案拍品
    private List<AuctionHomeParser.AuctionHomeSpinfo> spinfoList = new ArrayList<AuctionHomeParser.AuctionHomeSpinfo>();//推荐专场模块
    private List<RecomAuctionListParser> recomAuctionList = new ArrayList<RecomAuctionListParser>();//近期拍卖
    private List<RecomAuctionListParser> recomAuctionList_more = new ArrayList<RecomAuctionListParser>();//近期拍卖
    private ArrayList<String> listLotIds = new ArrayList<>();//拍品ID集合，主要是实现可以左右滑动
    private LinearLayout titlemore;
    private String imgwide;// 请求的图片宽度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
//        HindStatusBar();
        setContentView(R.layout.activity_auctionhome);
        initView();
    }

    @Override
    public void onStop() {
        super.onStop();
        //停止轮播
        mMyAdGallery.stopTimer();
    }

    public void onRestart() {
        super.onRestart();
        //启动轮播
        mMyAdGallery.startTimer();
    }


    private void initView() {
        mContext = AuctionHomeActivity.this;
        mSharePre = MySharedPreferences.getMySharedPreferences(mContext);
        imgwide = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 1) + "";
        titleRL = (RelativeLayout) findViewById(R.id.AuctionHome_titleRL);
        backBtn = (ImageView) findViewById(R.id.AuctionHome_title_backBtn);
        backBtn.setOnClickListener(this);
        shareBtn = (ImageView) findViewById(R.id.AuctionHome_title_shareBtn);
        shareBtn.setOnClickListener(this);
        auctionHome_RL = (RelativeLayout) findViewById(R.id.AuctionHome_RL);
//        titleHide_RL = (RelativeLayout) findViewById(R.id.AuctionHome_HideTitleRL);
//        titleHideBackBtn = (ImageView) findViewById(R.id.AuctionHome_HideTitle_backBtn);
//        titleHideBackBtn.setOnClickListener(this);
        HideTitleName = (TextView) findViewById(R.id.AuctionHome_HideTitle_titleName);
//        titleHideShareBtn = (ImageView) findViewById(R.id.AuctionHome_HideTitle_shareBtn);
//        titleHideShareBtn.setOnClickListener(this);
        lunbo = (RelativeLayout) findViewById(R.id.rel_lunbo);
        titlemore = (LinearLayout) findViewById(R.id.ll_titlemore);

        imgHeight = NetUtils.dip2px(mContext, 150) + "";
        mMyAdGallery = (MyAdGallery) findViewById(R.id.AuctionHome_MyAdGallery);
        mMyAdGallery.setMyOnItemClickListener(onAdGalleryClick);
        mMyAdGalleryGroup = (ViewGroup) findViewById(R.id.AuctionHome_MyAdGallery_viewGroup);
        mPullableScrollView = (PullableScrollView) findViewById(R.id.AuctionHome_PullableScrollView);
        mPullableScrollView.isDrop = false;//禁止下拉刷新
//        mPullableScrollView.setOnScrollListener(scrollListener);
        mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.refresh_layout);
        //mPullToRefreshLayout.setCanPullup(false);//禁止加载更多
        pastAuctionBtn = (RelativeLayout) findViewById(R.id.AuctionHome_PastAuctionBtn);
        pastAuctionBtn.setOnClickListener(this);
        auctionCatalogueBtn = (RelativeLayout) findViewById(R.id.AuctionHome_AuctionCatalogueBtn);
        auctionCatalogueBtn.setOnClickListener(this);
        celebritySealBtn = (RelativeLayout) findViewById(R.id.AuctionHome_CelebritySealBtn);
        celebritySealBtn.setOnClickListener(this);
        mechanismBtn = (RelativeLayout) findViewById(R.id.AuctionHome_MechanismBtn);
        mechanismBtn.setOnClickListener(this);
        CertificationItemsRL = (RelativeLayout) findViewById(R.id.AuctionHome_CertificationItemsRL);
        CertificationItemsRL.setOnClickListener(this);
        hotSpecialRL = (RelativeLayout) findViewById(R.id.AuctionHome_HotSpecialRL);
        hotSpecialRL.setOnClickListener(this);
        mHorizonListview_CertificationItems = (HorizonListviewNestingListView) findViewById(R.id.AuctionHome_CertificationItems_HorizontalListView);
        mHorizonListview_CertificationItems.setOnItemClickListener(onCertificationItemsItem);
        mHorizonListview_HotSpecial = (HorizonListviewNestingListView) findViewById(R.id.AuctionHome_HotSpecial_HorizontalListView);
        mHorizonListview_HotSpecial.setOnItemClickListener(onHotSpecialItem);
        mListView = (MyListView) findViewById(R.id.AuctionHome_RecentAuction_ListView);
        mListView.setOnItemClickListener(onListViewItem);
        mPullToRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                // TODO Auto-generated method stub
                //下拉刷新
                page = 1;
                isRefreshed = true;
                getRecomAuctionListDate();
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                // TODO Auto-generated method stub
                //上拉加载
                page++;
                getRecomAuctionListDate();
            }
        });
        int length = (Integer.valueOf(NetUtils.getDisplayMetrics(AuctionHomeActivity.this).get(NetUtils.DM_WIDTH)) - NetUtils.dip2px(mContext, 50)) / 4 + NetUtils.dip2px(mContext, 20);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) titlemore.getLayoutParams();
        lp.height = length;
        titlemore.setLayoutParams(lp);
        int Vheight = Integer.valueOf(NetUtils.getDisplayMetrics(AuctionHomeActivity.this).get(NetUtils.DM_WIDTH)) / 2;
        LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) lunbo.getLayoutParams(); //取控件textView当前的布局参数
        linearParams.height = Vheight;// 控件的高强制设成宽度的一半
        lunbo.setLayoutParams(linearParams);
        strCacheView = mSharePre.getValue(TAG_CACHE_VIEW,"");
        if (!TextUtils.isEmpty(strCacheView)){
            setHomeDate(strCacheView);
        }
        strCacheList = mSharePre.getValue(TAG_CACHE_LIST,"");
        if (!TextUtils.isEmpty(strCacheList)){
            setRecomAuctionListDate(strCacheList);
        }
        getHomeDate();
        getRecomAuctionListDate();
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.AuctionHome_title_backBtn:
                //轮播图上的返回键
                finish();
                break;
            case R.id.AuctionHome_title_shareBtn:
                //轮播图上的搜索键
                intent = new Intent(mContext, LotSearchActivity.class);
                startActivity(intent);
                break;
//            case R.id.AuctionHome_HideTitle_backBtn:
//                //隐藏标题的返回键
//                finish();
//                break;
//            case R.id.AuctionHome_HideTitle_shareBtn:
//                //隐藏标题的搜索键
//                intent = new Intent(mContext, LotSearchActivity.class);
//                startActivity(intent);
//                break;

            case R.id.AuctionHome_PastAuctionBtn:
                //往期拍卖
                intent = new Intent(mContext, AuctionPastAuction_Activity.class);
                startActivity(intent);
                break;
            case R.id.AuctionHome_AuctionCatalogueBtn:
                //拍卖图录
                intent = new Intent(mContext, AuctionCatalogueActivity.class);
                startActivity(intent);
                break;
            case R.id.AuctionHome_CelebritySealBtn:
                //名人印谱
                intent = new Intent(mContext, CelebritySeal_Activity.class);
                startActivity(intent);
                break;
            case R.id.AuctionHome_MechanismBtn:
                //合作机构
                intent = new Intent(mContext, AuctionOrganizationActivity.class);
                startActivity(intent);
                break;
            case R.id.AuctionHome_CertificationItemsRL:
                //更多鉴证拍品
                intent = new Intent(mContext, AuctionLotListActivity.class);
                startActivity(intent);
                break;
            case R.id.AuctionHome_HotSpecialRL:
                //更多热门专场
                intent = new Intent(mContext, AuctionSpecial_Activity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 轮播图点击事件
     */
    MyAdGallery.MyOnItemClickListener onAdGalleryClick = new MyAdGallery.MyOnItemClickListener() {

        @Override
        public void onItemClick(int curIndex) {
            // TODO Auto-generated method stub
            if (advsList != null && advsList.size() != 0) {
                Intent intent;
                if ("0".equals(advsList.get(curIndex).getType())) {
                    //Web页面
                    ShareItem item = new ShareItem();
                    item.setContent(advsList.get(curIndex).getInfo());
                    item.setId(advsList.get(curIndex).getCat_id());
                    item.setImageUrl(advsList.get(curIndex).getImgurl());
                    item.setTitle(advsList.get(curIndex).getTitle());
                    item.setUrl(advsList.get(curIndex).getLinkurl());
                    intent = new Intent(mContext, WebViewActivity.class);
                    intent.putExtra("url", advsList.get(curIndex).getLinkurl());
                    intent.putExtra("title", advsList.get(curIndex).getTitle());
                    intent.putExtra("type", AppUrl.LOAD_WEB_WITH_TITLE);
                    intent.putExtra("share", item);
                    startActivity(intent);
                } else if ("1".equals(advsList.get(curIndex).getType())) {
                    //机构
                    intent = new Intent(mContext, AucOrgDetActivity.class);
                    intent.putExtra("id", advsList.get(curIndex).getCat_id());
                    startActivity(intent);
                } else if ("2".equals(advsList.get(curIndex).getType())) {
                    //拍卖
                    intent = new Intent(mContext, AuctionInfo_Activity.class);
                    intent.putExtra("auctionID", advsList.get(curIndex).getCat_id());
                    intent.putExtra("SpecialListData", 1);
                    startActivity(intent);
                } else if ("3".equals(advsList.get(curIndex).getType())) {
                    //专场
                    intent = new Intent(mContext, AuctionSpecialInfo_Activity.class);
                    intent.putExtra("SpecialID", advsList.get(curIndex).getCat_id());
                    startActivity(intent);
                } else if ("4".equals(advsList.get(curIndex).getType())) {
                    //拍品
                    Intent intent2 = new Intent(mContext, LotDetailPagerActivity.class);
                    intent2.putExtra("id", advsList.get(curIndex).getCat_id());
                    startActivity(intent2);
                }
            }
        }
    };

    /**
     * 认证拍品Item点击事件
     */
    HorizonListviewNestingListView.OnItemClickListener onCertificationItemsItem = new HorizonListviewNestingListView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long arg3) {
            // TODO Auto-generated method stub

            Intent intent = new Intent(mContext, LotDetailPagerActivity.class);
            intent.putStringArrayListExtra("id", listLotIds);
            intent.putExtra("index", position);
            startActivity(intent);
        }
    };

    /**
     * 热门专场Item点击事件
     */
    HorizonListviewNestingListView.OnItemClickListener onHotSpecialItem = new HorizonListviewNestingListView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long arg3) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(mContext, AuctionSpecialInfo_Activity.class);
            intent.putExtra("SpecialID", spinfoList.get(position).getSp_id());
            startActivity(intent);
        }
    };

    /**
     * 近期拍卖Item点击事件
     */
    OnItemClickListener onListViewItem = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long arg3) {
            // TODO Auto-generated method stub
            Intent i = new Intent(mContext, AuctionInfo_Activity.class);
            i.putExtra("auctionID", recomAuctionList_more.get(position).getId());
            i.putExtra("SpecialListData", 0);
            startActivity(i);
        }
    };

    /**
     * 获取首页数据
     */
    private void getHomeDate() {
        isRequs = true;
        VolleyBasic.getInstance(this).post(Cache.auctionHome_bannerList,
                VolleyMap.getInstance().auctionHome_bannerList(imgHeight, imgHeight),
                AuctionHomeParser.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub\
                        mSharePre.setValue(TAG_CACHE_VIEW,vd.getJson());
                        setHomeDate(vd.getJson());
                        isRequs = false;
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                    }
                });
    }
    void setHomeDate(String json){
        VolleyData vd = new VolleyData(json,AuctionHomeParser.class);
        AuctionHomeParser mBean = (AuctionHomeParser) vd.getData();
        advsList = mBean.getAdvs();
        lotinfoList = mBean.getLotinfo();
        spinfoList = mBean.getSpinfo();
        mMyAdGalleryUrl = new ArrayList<String>();
        mMyAdGallery.removeAllViewsInLayout();
        if (advsList != null && advsList.size() != 0) {
            //获取轮播图数据
            for (int i = 0; i < advsList.size(); i++) {
                mMyAdGalleryUrl.add(advsList.get(i).getImgurl());
            }
            String[] imageData = new String[mMyAdGalleryUrl.size()];
            for (int i = 0; i < mMyAdGalleryUrl.size(); i++) {
                imageData[i] = mMyAdGalleryUrl.get(i).toString();
            }
            if (isRequs)
            mMyAdGallery.startNotFxed(mContext, imageData, null, 3000, mMyAdGalleryGroup, R.drawable.point_pressed, R.drawable.point_unpressed);
        }
        adapter_CertificationItems = new CertificationItems_Adapter(mContext, lotinfoList);
        mHorizonListview_CertificationItems.setAdapter(adapter_CertificationItems);
        adapter_HotSpecial = new HotSpecial_Adapter(mContext, spinfoList);
        mHorizonListview_HotSpecial.setAdapter(adapter_HotSpecial);
        listLotIds.clear();
        for (int i = 0; i < lotinfoList.size(); i++) {
            String idString = lotinfoList.get(i).getLot_id();
            listLotIds.add(idString);
        }
    }
    /**
     * 获取近期拍卖数据
     */
    private void getRecomAuctionListDate() {
        VolleyBasic.getInstance(this).post(Cache.recomAuctionList,
                VolleyMap.getInstance().recomAuctionList(imgwide,page),
                RecomAuctionListParser.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        if (page==1)
                        mSharePre.setValue(vd.getJson(),TAG_CACHE_LIST);

                       setRecomAuctionListDate(vd.getJson());
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        mPullToRefreshLayout.loadmoreFinish(mPullToRefreshLayout.FAIL);
                    }
                });
    }
    void setRecomAuctionListDate(String json){
        VolleyData vd = new VolleyData(json,RecomAuctionListParser.class);
        mPullToRefreshLayout.loadmoreFinish(mPullToRefreshLayout.SUCCEED);
        recomAuctionList = (List<RecomAuctionListParser>) vd.getList();
        if (isRefreshed == true) {
            recomAuctionList_more.clear();
            isRefreshed = false;
        }
        if (!recomAuctionList.isEmpty()) {
            recomAuctionList_more.addAll(recomAuctionList);
        }

        if (adapter_RecentAuction == null) {
            adapter_RecentAuction = new RecentAuction_Adapter(mContext, recomAuctionList_more);
            mListView.setAdapter(adapter_RecentAuction);
        }
        adapter_RecentAuction.notifyDataSetChanged();
    }
    public int getScrollY() {
        int top = mMyAdGallery.getTop();
        return -top;
    }

//    /**
//     * ScrollListener滚动监听
//     */
//    PullableScrollView.OnScrollListener scrollListener = new PullableScrollView.OnScrollListener() {
//        @Override
//        public void onScroll(int scrollY) {
//            int a = getScrollY();
//            if (scrollY > VeDate.dip2px(mContext, 320) - 70) {
//                if (titleHide_RL.getVisibility() == View.GONE) {
//                    setShowAnimation(titleHide_RL, 500);
//                }
//            } else {
//                if (titleHide_RL.getVisibility() == View.VISIBLE) {
//                    setHideAnimation(titleHide_RL, 500);
//                }
//            }
//            Log.e("Y", "getScrollY=" + a);
//            Log.e("Y", "scrollY=" + scrollY);
//        }
//    };


    private AlphaAnimation mHideAnimation = null;
    private AlphaAnimation mShowAnimation = null;

    /**
     * View渐隐动画效果
     */
    private void setHideAnimation(final View view, int duration) {
        if (null == view || duration < 0) {
            return;
        }
        if (null != mHideAnimation) {
            mHideAnimation.cancel();
        }
        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(duration);
        // mHideAnimation.setFillAfter(true);
        mHideAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                // TODO Auto-generated method stub
                view.clearAnimation();
                view.setVisibility(View.GONE);
            }
        });
        view.startAnimation(mHideAnimation);
    }

    /**
     * View渐现动画效果
     */
    private void setShowAnimation(final View view, int duration) {
        if (null == view || duration < 0) {
            return;
        }
        if (null != mShowAnimation) {
            mShowAnimation.cancel();
        }
        mShowAnimation = new AlphaAnimation(0.0f, 1.0f);
        mShowAnimation.setDuration(duration);
        // mShowAnimation.setFillAfter(true);
        mShowAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                // TODO Auto-generated method stub
                view.clearAnimation();
            }
        });
        view.startAnimation(mShowAnimation);
    }

    //透明状态栏
    private void HindStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            // Translucent status bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }
}
